home *** CD-ROM | disk | FTP | other *** search
- Path: munnari.OZ.AU!metro!metro!OzEmail!usenet
- From: rwilson@ozemail.com.au (Ross Wilson)
- Newsgroups: comp.lang.c
- Subject: Re: Newbie C question
- Date: Sun, 25 Feb 1996 01:40:58 GMT
- Organization: OzEmail Pty Ltd - Australia
- Message-ID: <4gob7t$8m3@oznet11.ozemail.com.au>
- References: <Dn4us9.Mu@undergrad.math.uwaterloo.ca>
- NNTP-Posting-Host: slcan1p05.ozemail.com.au
- X-Newsreader: Forte Free Agent 1.0.82
-
- sckettle@undergrad.math.uwaterloo.ca (Steve Kettle) wrote:
-
- >Hi, how the heck does one convert the error codes found in <errno.h>
- >to strings? I heard about a perror function but can't find it.
-
- >Thanks!
- >Steve.
- >--
-
- Steve,
-
- there is indeed a perror() function that should be supported by your
- compiler - look in the on-line docs that your compiler may have.
-
- My compiler (BC++ 4.52) says:
-
- ===================================================
- Syntax
-
- #include <stdio.h>
- void perror(const char *s);
-
- Description
-
- Prints a system error message.
- perror prints to the stderr stream (normally the console) the system
- error message for the last library routine that set the global
- variable errno.
- It prints the argument s followed by a colon (:) and the message
- corresponding to the current value of the global variable errno and
- finally a new line. The convention is to pass the file name of the
- program as the argument string.
- ===================================================
-
- An example (stdio.h, etc included):
-
- char *fname = "file.txt";
- FILE *fp;
-
- fp = fopen(fname, "r"):
- if (fp == NULL)
- {
- perror(fname);
- exit(EXIT_FAILURE);
- }
-
-
- I don't use perror() much as I usually want to do more than it
- provides, such as pass an error string to an error handler. A more
- flexible function is strerror() that does a simple 'errno' to 'string
- describing the error' conversion:
-
- ===================================================
- Syntax
-
- #include <string.h>
- char *strerror(int errnum);
-
- Description
-
- Returns a pointer to an error message string.
- strerror takes an int parameter errnum, an error number, and returns a
-
- pointer to an error message string associated with errnum.
-
- Return Value
-
- strerror returns a pointer to a constructed error string. The error
- message string is constructed in a static buffer that is overwritten
- with each call to strerror.
- ===================================================
-
- An example of use (errno.h, string.h, etc included):
-
- char *fname = "file.txt";
- FILE *fp;
-
- fp = fopen(fname, "r"):
- if (fp == NULL)
- {
- fprintf(stderr, "Can't open file '%s' for input: %s\n",
- fname, strerror(errno)
- );
- exit(EXIT_FAILURE);
- }
-
-
- good luck
- Ross
-
-